#!/bin/bash

export ARCH=arm64  
#export MACHINE=vexpress
#export TARGET=arm-linux
export GDB_VERSION=8.0
export KERNEL_VERSION=4.19.1
export BUSYBOX_VERSION=1.25.1
export CROSS_COMPILE=aarch64-linux-gnu-


function download_linux() {
  if [ -e linux-${KERNEL_VERSION}.tar.xz ]
  then 
    echo linux-${KERNEL_VERSION}.tar.xz exist
  else 
    wget https://cdn.kernel.org/pub/linux/kernel/v4.x/linux-${KERNEL_VERSION}.tar.xz
  fi

  if [ -e linux-${KERNEL_VERSION} ]
  then 
    echo linux-${KERNEL_VERSION} exist
  else 
    tar xf linux-${KERNEL_VERSION}.tar.xz
  fi
}

function build_linux() {
  echo "build_linux ..."
  cd linux-${KERNEL_VERSION}
  #compile with defconfig for arm64 architecture.
  make ARCH=${ARCH} CROSS_COMPILE=${CROSS_COMPILE} defconfig
  make -j8 
  #make ${MACHINE}_defconfig  
  #make zImage -j8  
  #make modules -j8  
  #make dtbs 
  cd -
}
  
function copy_linux() {
  rm -rf arm64-linux-kernel
  mkdir arm64-linux-kernel  
  cp -fv linux-${KERNEL_VERSION}/arch/arm64/boot/Image arm64-linux-kernel/  
  #cp -fv linux-${KERNEL_VERSION}/arch/arm/boot/dts/*ca9.dtb arm-linux-kernel/  
  #cp -fv linux-${KERNEL_VERSION}/.config  arm64-linux-kernel/ 
}

function download_busybox() {
  if [ -e busybox-${BUSYBOX_VERSION}.tar.bz2 ]
  then 
    echo busybox-${BUSYBOX_VERSION}.tar.bz2 exist
  else 
    wget https://busybox.net/downloads/busybox-${BUSYBOX_VERSION}.tar.bz2
  fi

  if [ -e busybox-${BUSYBOX_VERSION} ]
  then 
    echo busybox-${BUSYBOX_VERSION} exist
  else 
    tar xf busybox-${BUSYBOX_VERSION}.tar.bz2
  fi
}

function build_busybox() {
  echo "build_busybox..."
  cd busybox-${BUSYBOX_VERSION}
  make defconfig #dynamic compilation, needs copying dynamic library 
  make CROSS_COMPILE=${CROSS_COMPILE}
  make install CROSS_COMPILE=${CROSS_COMPILE}
  cd -
}

function make_rootfs() {
 rm -rf rootfs
 mkdir -p rootfs/lib
 #copy dynamic library for rootfs, because we compile the busybox dynamically 
 cp -pvf /usr/aarch64-linux-gnu/lib/* rootfs/lib
 cp busybox-${BUSYBOX_VERSION}/_install/* rootfs/ -rf

 cd rootfs
 mkdir dev etc proc
 cd dev
 #create the communication console
 mknod console c 5 1
 mknod null c 1 3
 cd ../etc
 echo "::sysinit:/etc/init.d/rcS" > inittab
 echo "::respawn:-/bin/sh" >> inittab
 echo "::askfirst:-/bin/sh" >> inittab
 echo "::ctrlaltdel:/bin/umount -a -r " >> inittab
 mkdir init.d
 cd init.d
 echo "#!/bin/sh" > rcS 
 echo "mount -t proc proc /proc" >> rcS
 chmod +x ./rcS
 cd ../..
 find . | cpio -o -H newc > rootfs.cpio
 gzip -c rootfs.cpio > rootfs.cpio.gz
 cd ../
}


function build() {
  download_linux
  build_linux
  copy_linux 
  download_busybox
  build_busybox
  make_rootfs
}

build

echo "Done"


